package com.earthea.application.web.controller.common;

import cn.hutool.core.util.IdUtil;
import com.earthea.application.common.constant.ConfigConstants;
import com.earthea.application.common.entity.BaseResponse;
import com.earthea.application.common.enums.CacheEnum;
import com.earthea.application.common.enums.CaptchaType;
import com.earthea.application.system.domain.service.ISysConfigService;
import com.earthea.application.system.entity.response.CaptchaResponse;
import com.earthea.cache.CacheService;
import com.earthea.common.util.Base64;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码操作处理
 */
@RestController
@RequestMapping("/rest")
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public BaseResponse getCode() {
        CaptchaResponse response = BaseResponse.success(CaptchaResponse.class);
        boolean captchaEnabled = sysConfigService.getBoolean(ConfigConstants.SYS_CONFIG_CAPTCHA_ENABLED_KEY, true);
        response.setCaptchaEnabled(captchaEnabled);
        if (!captchaEnabled) {
            return response;
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheEnum.CAPTCHA_CODE.getCacheKey(uuid);

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = sysConfigService.getString(ConfigConstants.SYS_CONFIG_CAPTCHA_TYPE_KEY, CaptchaType.MATH.name());
        if (CaptchaType.MATH.name().equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (CaptchaType.CHAR.name().equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        } else {
            return BaseResponse.failed(ConfigConstants.SYS_CONFIG_CAPTCHA_TYPE_KEY + " param must be [MATH, CHAR]", CaptchaResponse.class);
        }

        cacheService.setex(verifyKey, code, ConfigConstants.CAPTCHA_TIMEOUT);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return BaseResponse.failed(e.getMessage(), CaptchaResponse.class);
        }
        response.setUuid(uuid);
        response.setImg(Base64.encode(os.toByteArray()));
        return response;
    }
}
